package adavance.thread.lockbank;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//取钱人
public class Taker extends Thread {
    private final Account ac;
    //策略锁
    //private static final Lock lock = new ReentrantLock();

    public Taker(String name, Account a) {
        super(name);
        this.ac = a;
    }

    @Override
    public void run() {
        Random r = new Random();
        int qu = 0;
        while (true) {
            qu = r.nextInt(500);
            try {
                System.out.println(super.getName() + "取钱" + qu + "元，当前账户余额是：" + ac.getMoney() + "元");
                //lock.lock();
                synchronized (ac) {
                    while (ac.getMoney() < qu) {
                        System.out.println(super.getName() + "等着！");
                        ac.wait();
                        System.out.println(super.getName() + "收到存钱的消息了，先检查余额，是" + ac.getMoney() + "元");
                    }
                    //钱还够，可以取
                    sleep(50);

                    ac.withdraw(qu);
                    System.out.println(super.getName() + "取钱" + qu + "元，当前账户余额是：" + ac.getMoney() + "元");
                }
            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                //lock.unlock();
            }

        }
    }
}
